import { useEffect, useState } from 'react';
import {
  splitFileUrl,
  downloadTemplate,
  getFileNameNotType,
  getUserName,
  getUserDepName,
  getInvoiceCode,
  getLoadMapList,
  getTenantID,
  getPersonalInfo,
  getPosName,
  getUserDepID,
  getUserID,
} from '@/utils';
import { useDescriptionsType } from '@/components/DescriptionsType';
import { Select, Tooltip, TreeSelect, message, Switch, Button } from 'antd';
import { AssetTableView } from '../mview/AssetTableView';
import { UploadFormCommon } from '@/components/UploadForm';
import MyIcon from '@/components/MyIcon';
import { getFlowOrgTreeByOrgIDService } from '@/services/BaseLayout';
import { handleNotPostion } from '@/pages/ContractController/ContractManage/mconfig';
import { getUserDataList } from '@/components/SchemaComponent/SchemaManage/hooks';
import { MaterialTableView } from '../mview/MaterialTableView';
import { useAcquisitionManageReducer } from './useManageReducer';
import { ILoadMapTypeAll } from '@/common';
import moment from 'moment';
import { TagSelectNew as TagSelect } from '@/components/TagSelectNew';
import { IAcquisitionActionEnum } from '../mconfig';
import { getBaseUrl } from '@/services/urlconst';
import { readReadShowFileService } from '@/services/BaseLayout';
import { EyeOutlined, DownloadOutlined } from '@ant-design/icons';

/** 领用/退库 表单页配置项 */
const getUpdateConfig = ({
  pageType,
  tkObj,
  openAssetModalFun,
  openMaterialModalFun,
  useReturnForm,
  setSelectUserInfoFun,
  detailInfo,
  storeTreeList,
  getStorageLoading,
  editState,
  changeEditAssetId,
  finish,
  acquisitionDispatch,
  openReadAssetModalFun,
  handleEditSave,
  onClickExportAssetsMaterials,
  curRes,
}) => {
  /** 申请类型 */
  const [queryType, setQueryType] = useState<null | number>(1);

  const [busiFlag, setBusiFlag] = useState<undefined | number>(undefined);

  /** 引入上下文 */
  const { assetList, materialList } = useAcquisitionManageReducer();

  /** 领用/退库类型 */
  const [applyTypeState, setApplyTypeState] = useState<any>(null);

  /** 展示处置材料类型 */
  const [isHiddenState, setIsHiddenState] = useState<boolean>(true);

  /**获取用户接口 */
  const { getUserRun, getUserLoading, getUserList } = getUserDataList();

  /** 获取组织机构树接口 */
  const { getFlowOrgTreeRun, getFlowOrgTreeLoading, getFlowOrgList } = getFlowOrgTreeByOrgIDService();

  /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.ASSET_AREA}`, //资产存放地点
  ]);

  /** 轻阅读预览 */
  const { readReadShowFileRun } = readReadShowFileService();

  /**轻阅读预览 */
  const onOpenReadOfdWord = (fieldUrl: string) => {
    readReadShowFileRun({ fieldPath: `${getBaseUrl()}${fieldUrl}` });
  };

  useEffect(() => {
    if (queryType == 2 && (applyTypeState == 0 || applyTypeState == 2)) {
      setIsHiddenState(false);
    } else {
      setIsHiddenState(true);
    }
  }, [queryType, applyTypeState]);

  /** 切换表单 */
  useEffect(() => {
    /** 初始化请求组织机构 */
    let payload = {
      params: '0',
      flowType: '0',
    };
    getFlowOrgTreeRun(payload);

    /** 初始化请求使用人 */
    const pageSize = {
      page: 1,
      rows: 10000,
    };
    // getUserRun(pageSize);
    getUserRun({ userDepartmentID: getUserDepID() });
  }, []);

  useEffect(() => {
    if (detailInfo?.id) {
      // 回填表单
      methods?.setFieldsValue({
        ...detailInfo,
        createTime: detailInfo?.createTime ? moment(detailInfo?.createTime) : undefined,
        backTime: detailInfo?.backTime ? moment(detailInfo?.backTime) : undefined,
      });
      setBusiFlag(detailInfo?.busiFlag);
    } else {
      // 我的资产跳转过来的退库
      if (Object.keys(tkObj).length !== 0) {
        setQueryType(2);
        methods?.setFieldsValue({
          ...tkObj,
          queryType: '2',
          applyType: 1,
          createTime: detailInfo?.createTime ? moment(detailInfo?.createTime) : undefined,
          backTime: detailInfo?.backTime ? moment(detailInfo?.backTime) : undefined,
        });
      } else {
        let strVal = queryType == 1 ? '领用' : queryType == 2 ? '退库' : queryType == 3 ? '借用' : queryType == 4 ? '归还' : '--';
        methods?.setFieldsValue({
          createTime: moment(new Date()),
          applyCode: getInvoiceCode('LY'),
          queryType,
          useType: '1',
          applyTitle: `${getUserName()}_${getUserDepName()}_${moment(new Date()).format('YYYY年_MM月')}_${strVal}`,
          userID: getUserID(),
          createrName: getUserName(),
          createPhone: getPersonalInfo()?.phoneMobile || '',
          createDepartmentName: getUserDepName(),
          createPositionName: getPosName(),
          useDepartmentID: getUserDepID(),
          busiFlag: 0,
        });
      }
    }

    if (Object.keys(tkObj).length !== 0) {
      setApplyTypeState(1);
      setQueryType(2);
    } else {
      setApplyTypeState(detailInfo?.applyType);
      if (detailInfo?.queryType && detailInfo?.queryType != '1') {
        setQueryType(detailInfo?.queryType);
      }
    }
  }, [detailInfo]);

  const disabled: boolean = pageType === 'detail';

  /** 表单配置 */
  const [config, methods] = useDescriptionsType({
    labelWidth: 190,
    basicForm: useReturnForm,
    isShowNumTitle: false,
    name: 'accept-addAndEdit',
    schemas: [
      {
        key: 'accept-basic',
        title: '一、基本信息',
        fieldChildren: [
          {
            label: '申请日期',
            field: 'createTime',
            component: 'DatePicker',
            placeholder: '请选择申请日期',
            disabled: disabled,
            required: true,
            disabledDate: (current) => {
              return current && current > moment(new Date(), 'YYYY-MM-DD');
            },
          },
          {
            field: `applyCode`,
            label: `流水单号`,
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
          },
          {
            label: '申请人',
            field: 'createrName',
            component: 'Input',
            placeholder: '自动带出',
            disabled: true,
          },
          {
            label: '联系电话',
            field: 'createPhone',
            component: 'Input',
            placeholder: '自动带出',
            disabled: true,
          },
          {
            label: '申请部门/单位',
            field: 'createDepartmentName',
            component: 'Input',
            placeholder: '自动带出',
            disabled: true,
          },
          {
            label: '职务岗位',
            field: 'createPositionName',
            component: 'Input',
            placeholder: '自动带出',
            disabled: true,
          },
          {
            field: `queryType`,
            label: `申请类型`,
            component: 'Render',
            required: !disabled,
            placeholder: '请选择',
            disabled: disabled || pageType === 'edit',
            // colSpan: 2,
            render(text, record) {
              if (disabled) {
                return text ? (text == '1' ? '领用' : text == '2' ? '退库' : text == '3' ? '借用' : text == '4' ? '归还' : '--') : '--';
              } else {
                return (
                  <TagSelect
                    colSpan={24}
                    formLabel={''}
                    formName={'queryType'}
                    defalultKeys={text || '1'}
                    onChange={(value) => {
                      setQueryType(value);
                      let strVal = value == '1' ? '领用' : value == '2' ? '退库' : value == '3' ? '借用' : value == '4' ? '归还' : '--';
                      methods?.setFieldsValue({
                        busiFlag: 0,
                        applyTitle: `${getUserName()}_${getUserDepName()}_${moment(new Date()).format('YYYY年_MM月')}_${strVal}`,
                      });
                      acquisitionDispatch({
                        type: IAcquisitionActionEnum.CANCEL_ASSET,
                        payload: [],
                      });
                      acquisitionDispatch({
                        type: IAcquisitionActionEnum.CANCEL_MATERIAL,
                        payload: [],
                      });
                    }}
                    radioDisabled={disabled || pageType === 'edit' || detailInfo?.id}
                    // radioDisabled={true}
                    radioList={[
                      {
                        value: '1',
                        name: '领用',
                      },
                      {
                        value: '2',
                        name: '退库',
                      },
                      {
                        value: '3',
                        name: '借用',
                      },
                      {
                        value: '4',
                        name: '归还',
                      },
                    ]}
                  />
                );
              }
            },
          },
          {
            field: `belongDepartmentID`,
            label: `货物所属部门`,
            required: !disabled,
            component: 'Render',
            disabled: disabled,
            placeholder: '请选择',
            initialValue: getUserDepID(),
            render: (text, record) => {
              if (disabled) {
                return detailInfo?.belongDepartmentName || '--';
              } else {
                return (
                  <TreeSelect
                    loading={getFlowOrgTreeLoading}
                    placeholder="请选择"
                    treeData={handleNotPostion(getFlowOrgList)}
                    disabled={pageType == 'detail' ? true : false}
                    showArrow={pageType == 'detail' ? false : true}
                    fieldNames={{
                      label: 'title',
                      value: 'id',
                      children: 'children',
                    }}
                    showSearch={true}
                    treeNodeFilterProp={'text'}
                    // defaultValue={getUserDepID()}
                  />
                );
              }
            },
          },

          {
            field: `userID`,
            label: `使用人`,
            component: 'Select',
            required: !disabled,
            ishidden: queryType == 2 || queryType == 4,
            placeholder: '请选择',
            contentAfter: <a onClick={openReadAssetModalFun}>名下资产</a>,
            colSpan: queryType == 1 ? 2 : queryType == 3 ? 1 : 1,
            render: (text, record) => {
              if (disabled) {
                return detailInfo?.userName || '--';
              } else {
                return (
                  <Select
                    placeholder={`请选择`}
                    loading={getUserLoading}
                    allowClear
                    showSearch
                    disabled={disabled}
                    defaultValue={text}
                    optionFilterProp={'searchtitle'}
                    // mode="multiple"
                    showArrow
                    maxTagCount={1}
                    onChange={(value, option: any) => {
                      setSelectUserInfoFun(option?.row);
                    }}
                  >
                    {getUserList && getUserList?.length > 0 ? (
                      <>
                        {getUserList?.map((item: any) => {
                          return (
                            <Select.Option value={item?.id} key={item?.id} searchtitle={item?.realName} row={item}>
                              <MyIcon style={{ marginRight: 5 }} type="icon-lianxiren" />
                              {item?.realName}
                            </Select.Option>
                          );
                        })}
                      </>
                    ) : (
                      <></>
                    )}
                  </Select>
                );
              }
            },
          },
          {
            field: `backTime`,
            label: `预计归还日期`,
            component: 'DatePicker',
            disabledDate: (current) => {
              if (!current) {
                return false;
              }
              return current.valueOf() < new Date().setHours(0, 0, 0, 0);
            },
            required: true,
            placeholder: disabled ? '--' : '请选择',
            disabled: disabled,
            ishidden: queryType != 3,
          },
          {
            field: `useType`,
            label: `用途类型`,
            component: 'Render',
            required: !disabled,
            disabled: disabled,
            ishidden: queryType == 2 || queryType == 4,
            placeholder: '请选择',
            // initialValue: '1',
            render(text, record) {
              if (disabled) {
                return text ? (text === '1' ? '自用' : '共用') : '--';
              } else {
                return (
                  <TagSelect
                    colSpan={24}
                    formLabel={''}
                    formName={'useType'}
                    defalultKeys={text || '1'}
                    radioDisabled={detailInfo?.checkState || disabled}
                    radioList={[
                      {
                        value: '1',
                        name: '自用',
                      },
                      {
                        value: '0',
                        name: '共用',
                      },
                    ]}
                  />
                );
              }
            },
          },
          {
            field: `applyType`,
            // label: queryType == '1' || queryType == null ? `领用类型` : `退库类型`,
            label: '货物类型',
            component: 'Render',
            required: !disabled,
            disabled: detailInfo?.checkState || disabled,
            colSpan: ((applyTypeState == 0 || applyTypeState == 2) && queryType == 2) || queryType == 1 || queryType == 3 ? 1 : 2,
            message: '请选择货物类型',
            render(text: any, record) {
              if (disabled) {
                return text == 0 ? '资产&材料' : text == 1 ? '资产' : text == 2 ? '材料' : '--';
              } else {
                return (
                  <TagSelect
                    colSpan={24}
                    formLabel={''}
                    formName={'applyType'}
                    radioDisabled={detailInfo?.checkState || disabled}
                    onChange={(value) => {
                      setApplyTypeState(value);
                      acquisitionDispatch({
                        type: IAcquisitionActionEnum.CANCEL_ASSET,
                        payload: [],
                      });
                      acquisitionDispatch({
                        type: IAcquisitionActionEnum.CANCEL_MATERIAL,
                        payload: [],
                      });
                    }}
                    defalultKeys={text || null}
                    radioList={[
                      {
                        value: 0,
                        name: '资产&材料',
                      },
                      {
                        value: 1,
                        name: '资产',
                      },
                      {
                        value: 2,
                        name: '材料',
                      },
                    ]}
                  />
                );
              }
            },
          },
          {
            field: `handleType`,
            label: '材料处置类型',
            component: 'Render',
            required: !disabled,
            disabled: disabled,
            ishidden: isHiddenState,
            initialValue: '0',
            colSpan: 1,
            render(text, record) {
              if (disabled) {
                return text ? (text === '0' ? '正常退库' : '报废处置') : '--';
              } else {
                return (
                  <TagSelect
                    formLabel={''}
                    formName={'handleType'}
                    radioDisabled={disabled}
                    radioList={[
                      {
                        value: '0',
                        name: '正常退库',
                      },
                      {
                        value: '1',
                        name: '报废处置',
                      },
                    ]}
                  />
                );
              }
            },
          },
          {
            field: `busiFlag`,
            label: `是否归口部门审批`,
            component: 'Render',
            required: !disabled,
            disabled: detailInfo?.checkState || disabled,
            placeholder: '请选择',
            colSpan: busiFlag === 1 ? 1 : 2,
            ishidden: queryType == 2 || queryType == 4,
            // initialValue: '1',
            render(text, record) {
              if (disabled) {
                return text?.toString() ? (text?.toString() === '1' ? '是' : '否') : '--';
              } else {
                return (
                  <Switch
                    disabled={detailInfo?.checkState || disabled}
                    checkedChildren="是"
                    unCheckedChildren="否"
                    checked={Number(text) == 1 ? true : false}
                    onChange={(checked) => {
                      setBusiFlag(checked ? 1 : 0);
                      methods?.setFieldsValue({
                        busiFlag: checked ? 1 : 0,
                        busiDepartmentID: '',
                      });
                    }}
                  />
                );
              }
            },
          },
          {
            field: `busiDepartmentID`,
            label: `归口部门`,
            ishidden: !(busiFlag === 1 && (queryType == 1 || queryType == 3)),
            component: 'Render',
            disabled: true,
            message: '请选择归口部门',
            placeholder: '请选择',
            required: !disabled,
            render: (text) => {
              if (pageType == 'detail') {
                return <span>{detailInfo?.busiDepartmentName || '--'}</span>;
              } else {
                return (
                  <TreeSelect
                    loading={getFlowOrgTreeLoading}
                    placeholder="请选择"
                    treeData={handleNotPostion(getFlowOrgList)}
                    disabled={pageType == 'detail' ? true : false}
                    showArrow={pageType == 'detail' ? false : true}
                    fieldNames={{
                      label: 'title',
                      value: 'id',
                      children: 'children',
                    }}
                    showSearch={true}
                    treeNodeFilterProp={'text'}
                    allowClear={true}
                    // onSelect={(_value, node) => {
                    //   if (node) {
                    //     methods?.setFieldsValue({
                    //       busiDepartmentName: node?.text,
                    //     });
                    //     // }
                    //   }
                    // }}
                  />
                );
              }
            },
          },
          {
            field: `applyInfo`,
            label: `申请理由`,
            component: 'InputTextArea',
            disabled: detailInfo?.checkState || disabled,
            placeholder: '请输入',
            required: !disabled,
            colSpan: 2,
            allowClear: true,
            showCount: true,
            maxLength: 200,
            autoSize: { minRows: 2, maxRows: 4 },
          },
          {
            field: `applyFile`,
            label: `相关附件`,
            colSpan: 1,
            component: 'Render',
            disabled: disabled,
            placeholder: '请上传',
            render: (text, record) => {
              return (
                <>
                  {disabled || detailInfo?.checkState ? (
                    <>
                      <div style={{ height: '100%', display: 'flex', alignItems: 'center', marginLeft: '8px' }}>
                        {record?.['applyFile']
                          ? splitFileUrl(record?.['applyFile'])?.map((e, i) => {
                              return (
                                <div>
                                  <Tooltip title={e.attachName} key={new Date().getTime() * 25615265152 + e?.attachName}>
                                    <a
                                      onClick={() => {
                                        message.success('下载中，请稍后...');
                                        downloadTemplate('/assetInfo/downloadFile', e?.attachName, e?.attachUrl, () => {});
                                      }}
                                    >
                                      <MyIcon type="icon-file-text-fill" />
                                      &nbsp;
                                      {getFileNameNotType(e.attachName, 8)}
                                    </a>
                                  </Tooltip>
                                  {/* 轻阅读预览 */}
                                  <Tooltip title={'在线预览'}>
                                    <Button type="link" size="small" onClick={() => onOpenReadOfdWord(e?.attachUrl)} icon={<EyeOutlined />} />
                                  </Tooltip>
                                </div>
                              );
                            })
                          : '--'}
                      </div>
                    </>
                  ) : (
                    <UploadFormCommon
                      form={useReturnForm}
                      fileFormName={'applyFile'}
                      spanCol={24}
                      inRowProportion={24}
                      name={'attachFile'}
                      required={false}
                      fieldBusiPath={'assetFile'}
                      defaultFiles={text}
                      url={'/assetInfo/uploadFile'}
                      downloadUrl={'/assetInfo/downloadFile'}
                      fileFormDelName={'delAttachUrl'}
                      delFunc={(delFilePath: string) => {
                        useReturnForm.setFieldValue('delAttachUrl', delFilePath);
                      }}
                      // accept={'.doc|.docx'}
                      // maxFile={10}
                      // hintTitle={'且只能上传 1 个！'}
                      // isShowUploadBtn={true}
                    >
                      上传
                    </UploadFormCommon>
                  )}
                </>
              );
            },
          },
          {
            field: `applyTitle`,
            label: `事项名称`,
            component: 'Input',
            disabled: disabled,
            placeholder: '请输入',
            required: !disabled,
            colSpan: 0,
          },
        ],
      },
      {
        key: 'accept-asset',
        title:
          applyTypeState == 0 || applyTypeState == 1 ? (
            <div
              style={{
                display: 'flex',
                justifyContent: 'space-between',
              }}
            >
              <div style={{ minWidth: 150 }}></div>
              <div style={{ minWidth: 150 }}>二、资产明细</div>
              <div style={{ minWidth: 150, textAlign: 'right' }}>
                {detailInfo?.id &&
                  detailInfo?.state &&
                  detailInfo?.state != `${getTenantID()}${ILoadMapTypeAll.STORAGE_USE_STATUS}1000` &&
                  detailInfo?.state != `${getTenantID()}${ILoadMapTypeAll.STORAGE_RETURN_STATUS}1000` &&
                  curRes?.['/assetApplyUes/assetApplyNumberExport/{id}/{type}'] && (
                    <Button icon={<DownloadOutlined />} type="link" onClick={() => onClickExportAssetsMaterials(1)}>
                      导出资产
                    </Button>
                  )}
              </div>
            </div>
          ) : (
            ''
          ),
        fieldCustomDom: (
          <>
            {applyTypeState == 0 || applyTypeState == 1 || assetList?.length > 0 ? (
              <AssetTableView
                openAssetModalFun={openAssetModalFun}
                pageType={pageType}
                loadMapInfo={loadMapInfo}
                mapLoading={mapLoading}
                queryType={queryType}
                storeTreeList={storeTreeList}
                handleEditSave={handleEditSave}
                getStorageLoading={getStorageLoading}
                editState={editState}
                finish={finish}
                changeEditAssetId={changeEditAssetId}
                detailInfo={detailInfo}
              />
            ) : null}
          </>
        ),
      },
      {
        key: 'accept-material',
        title:
          applyTypeState == 0 || applyTypeState == 2 ? (
            <div
              style={{
                display: 'flex',
                justifyContent: 'space-between',
              }}
            >
              <div style={{ minWidth: 150 }}></div>
              <div style={{ minWidth: 150 }}>{applyTypeState == 2 ? '二、材料明细' : '三、材料明细'}</div>
              <div style={{ minWidth: 150, textAlign: 'right' }}>
                {detailInfo?.id &&
                  detailInfo?.state &&
                  detailInfo?.state != `${getTenantID()}${ILoadMapTypeAll.STORAGE_USE_STATUS}1000` &&
                  detailInfo?.state != `${getTenantID()}${ILoadMapTypeAll.STORAGE_RETURN_STATUS}1000` &&
                  curRes?.['/assetApplyUes/assetApplyNumberExport/{id}/{type}'] && (
                    <Button icon={<DownloadOutlined />} type="link" onClick={() => onClickExportAssetsMaterials(0)}>
                      导出材料
                    </Button>
                  )}
              </div>
            </div>
          ) : (
            ''
          ),
        fieldCustomDom: (
          <>
            {/* <Button icon={<DownloadOutlined />} type="primary">材料导出</Button> */}
            {applyTypeState == 0 || applyTypeState == 2 || materialList?.length > 0 ? (
              <MaterialTableView
                openMaterialModalFun={openMaterialModalFun}
                pageType={pageType}
                loadMapInfo={loadMapInfo}
                mapLoading={mapLoading}
                queryType={queryType}
                editState={editState}
              />
            ) : null}
          </>
        ),
      },
    ],
  });

  return {
    config,
    methods,
    colLoading: getFlowOrgTreeLoading,
  };
};

export { getUpdateConfig };

// {
//   field: `useDepartmentID`,
//   label: `使用部门`,
//   required: !disabled,
//   ishidden: queryType == '2',
//   component: 'Render',
//   disabled: disabled,
//   placeholder: '请选择',
//   render: (text, record) => {
//     if (disabled) {
//       return detailInfo?.useDepartmentName || '--';
//     } else {
//       return (
//         <TreeSelect
//           loading={getFlowOrgTreeLoading}
//           placeholder="请选择"
//           treeData={handleNotPostion(getFlowOrgList)}
//           disabled={pageType == 'detail' ? true : false}
//           showArrow={pageType == 'detail' ? false : true}
//           fieldNames={{
//             label: 'title',
//             value: 'id',
//             children: 'children',
//           }}
//           showSearch={true}
//           treeNodeFilterProp={'text'}
//           onChange={(value) => {
//             if (value) {
//               getUserRun({ userDepartmentID: value });
//             }
//             methods?.setFieldsValue({
//               userID: null,
//             });
//           }}
//         />
//       );
//     }
//   },
// },
